﻿using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;

namespace HashFoo.Rest.Server
{
    /// <summary>
    /// Simple <see cref="IControllerFactory"/> that will check if the <see cref="RequestContext"/>
    /// is for a <see cref="IServiceHandler{TRequest}"/>.  If so, returns its type, else uses the base implementation.
    /// </summary>
    /// <remarks>
    /// This controller factory doens't use any specific DI -- the idea is that hopefully you're using
    /// <see cref="IDependencyResolver"/> anyway.  This allows the factory to focus on getting the handler type if its a handler request.
    /// 
    /// If you want to write your own controller factory, you can use the <see cref="ResourceRouteUtil.GetHandlerTypeFromRequest"/> method
    /// to get the handler type from a <see cref="RequestContext"/>.
    /// </remarks>
    public class HandlerControllerFactory : DefaultControllerFactory
    {
        /// <summary>
        /// Checks if the <see cref="RequestContext"/>
        /// is for a <see cref="IServiceHandler{TRequest}"/>.  If so, returns its type, else uses the base implementation.
        /// </summary>
        /// <param name="requestContext"></param>
        /// <param name="controllerName"></param>
        /// <returns></returns>
        protected override Type GetControllerType(RequestContext requestContext, string controllerName)
        {
            return requestContext.GetHandlerTypeFromRequest(controllerName) ?? base.GetControllerType(requestContext, controllerName);
        }
    }
}